<template>
  <div class="area">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{$t('report.imAccessId')}}：</span>
                  <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div class="accs">
                  <el-checkbox v-model="positiveSessionCount">{{$t('report.ProductDialogueData')}}</el-checkbox>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.imReportSourceFromAreaTop10')"></affix>
    </div>
    <div :id="id">
      <el-row class="map">
        <el-col :span="12"><div id="ImsourceMap"></div></el-col>
        <el-col :span="12">
          <div class="top-title">{{$t('report.imReportSourceFromRank')}}</div>
            <el-row class="source-bar" v-for="(i, index) in top" :key="index">
              <el-col :span="2"  v-bind:class="[index < 3 ? colorClass : '']">{{index+1}}</el-col>
              <el-col :span="4">{{i.name}}</el-col>
              <el-col :span="12" class="top-all">
                <div  v-bind:style="{ backgroundColor: i.color, width: i.width }" class="top-short">
                </div>
              </el-col>
              <el-col :span="4">{{i.data}}</el-col>
            </el-row>
        </el-col>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                1. {{$t('report.allConSationNumber')}}<br>
                2. {{$t('report.imPersonSessionNum')}}<br>
                3. {{$t('report.imRobotSessionNum')}}<br>
                4. {{$t('report.imSeatInviteNum')}}<br>
                5. {{$t('report.initiatingNumber')}}<br>
                6. {{$t('report.imLostSessionCount')}}<br>
                7. {{$t('report.imTurnToPerson')}}<br>
                8. {{$t('report.imFineSessionNum1')}}<br>
                9. {{$t('report.imBadSessionNum1')}}<br>
                10. {{$t('report.imKindSessionNum1')}}<br>
                11. {{$t('report.imTurnCustomNum')}}<br>
                12. {{$t('report.imEveryClickNum')}}<br>
                13. {{$t('report.imEveryAskNum')}}<br>
                14. {{$t('report.visitorCount')}}<br>
                <span v-if="isTip">
                  15. {{$t('report.imReportLeaveNum')}}<br>
                  16. {{$t('report.imChanceTurnRate')}}<br>
                  17. {{$t('report.imLeaveRate')}}<br>
                  18. {{$t('report.imWebChanceNum')}}<br>
                  19. {{$t('report.imWebvisitNum')}}<br>
                  20. {{$t('report.activeClaimRobotSessionCount')}}<br>
                </span>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :config="headOptions.Config" :sum="totalData"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../../ui-modules/unfold/index.vue'
  import Highcharts from 'highcharts/highmaps'
  import data from '../../../../../../node_modules/highcharts/modules/data.js'
  import cnAllChina from '@/utils/cn-china-by-peng8.js'
  import dateTime from '../../base/datetime.vue'
  import reportTable from '../../base/reportTable.vue'
  import { deepClone, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, checkTime } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'

  data(Highcharts)
  Highcharts.setOptions({
    lang: {
      // drillUpText: '返回 > {series.name}' 钻入用的没有钻入
    }
  })
  export default {
    name: 'im_area',
    data () {
      return {
        positiveSessionCount: false, // 产生对话数的数据
        isFold: false, // 是否展示搜索条件
        selectedAccessIdList: [], // 接入号绑定值
        accessIdOptions: [], // 接入号渲染数据
        id: 'im_report_session_area', // 查询id
        title: this.$t('report.imReportSourceFromArea'),
        loading: false, // 查询时展示加载的开关
        query: {}, // 查询条件
        dialogVisible: false, // 导出pdf弹窗开关
        colorClass: 'colorClass', // class
        top10Colors: ['#985fac', '#ee596f', '#f48c4d', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1'], // top10颜色数组
        headOptions: { Config: [], data: [] }, // 表头数据
        serverData: [] // 原始查询table数据
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable
    },
    computed: {
      // 是否展示网站相关数据
      isTip () {
        if (!this.headOptions.Config || this.headOptions.Config.length === 0) {
          return false
        }
        let bool = false
        this.headOptions.Config.map(item => {
          if (item.name === 'userVisitCount' && item.show) {
            bool = true
          }
        })
        return bool
      },
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        return this.getTotalData(this.serverData, this.headOptions)
      },
      top () {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }

        let data = deepClone(this.serverData)
        data.sort((a, b) => b.sessionCount - a.sessionCount)
        data = data.slice(0, 10)

        return data.map((item, index) => ({
          width: data[0].sessionCount > 0 ? Math.round(80 * item.sessionCount / data[0].sessionCount) + '%' : 0,
          color: this.top10Colors[index],
          name: item.area,
          data: item.sessionCount
        }))
      },
      searchIndex () {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }

        let data = deepClone(this.serverData)

        return data.map(item => ({ name: item.area, data: item.sessionCount }))
      }
    },
    methods: {
      // 处理table数据
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)

        return data
      },
      // 计算table合计
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{area: this.$t('report.total')}]
        }
        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = {
          area: this.$t('report.total')
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
          }
        }
        total.userConsultRate = total.userVisitCount > 0 ? Math.round((total.userConsultCount / total.userVisitCount) * 100) : 0
        total.userConsultRate = total.userConsultRate > 100 ? 100 : total.userConsultRate
        total.userLeaveRate = total.userVisitCount > 0 ? Math.round((total.userLeaveCount / total.userVisitCount) * 100) : 0
        return [total]
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 地图配置
      renderMap () {
        let that = this
        let datakey = this.searchIndex
        let mapdata = Highcharts.geojson(cnAllChina)
        mapdata.forEach(function (item) {
          item.name = item.properties['cn-name']
          item.value = null
          for (var j = 0; j < datakey.length; j++) {
            if (datakey[j].name.indexOf(item.name) > -1) {
              item.value = datakey[j].data
              break
            }
          }
        })
        let option = {
          chart: {
            plotBackgroundColor: '#fff',
            events: {
            }
          },
          tooltip: {
            useHTML: true,
            formatter: function () {
              return '<div style="width:;">' + that.$t('report.imReportSourceFromAreaSearchIndex') + '<br /><span style="display:inline-block;width: 10px;height: 10px;border-radius: 50%;background-color:' + this.color + ';"></span>' + this.point.name + ':' + this.point.value + '</div>'
            }
          },
          credits: {
            href: 'javascript:goHome()',
            text: ''
          },
          title: {
            text: ''
          },
          subtitle: {
            text: this.$t('report.imReportSourceFromAreaSearchIndex') + ':',
            floating: true,
            align: 'left',
            y: 446,
            style: {
              fontSize: '12px'
            }
          },
          crop: true,
          legend: {
            x: 60,
            layout: 'align',
            align: 'left',
            verticalAlign: 'bottom'
          },
          colorAxis: {
            min: 0,
            allowDecimals: false,
            minColor: '#B5DAFD',
            maxColor: '#07134F',
            stops: [
              [0, '#B5DAFD'],
              [0.67, '#0E51F0'],
              [1, '#07134F']
            ]
          },
          mapNavigation: {
            enabled: true,
            enableMouseWheelZoom: false,
            enableDoubleClickZoom: false,
            buttonOptions: {
              verticalAlign: 'bottom'
            }
          },
          plotOptions: {
            map: {
              borderColor: '#fff',
              nullColor: '#E1EEFA'
            }
          },
          series: [{
            data: mapdata,
            name: this.$t('report.imReportChina'),
            color: '',
            dataLabels: {
              enabled: false
            },
            states: {
              hover: {
                brightness: 0.07,
                borderColor: '#fff'
              }
            }
          }]
        }
        Highcharts.mapChart(document.getElementById('ImsourceMap'), option)
      },
      // 查询数据的条件
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
           // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.positiveSessionCount = this.positiveSessionCount
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      // 查询方法
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryImSessionFromReport', queryData).then((res) => {
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)

          this.serverData = deepClone(res.data) || this.serverData
          this.renderMap()
          this.loading = false
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryImSessionFromReport', queryData).then((res) => {
          this.loading = false
          // 表头
          var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
          var serverData = deepClone(res.data) || []

          var tableData = this.getTableData(serverData, headOptions)
          var headers = headOptionsToXlsxHeaders(headOptions.Config)
          if (tableData && tableData.length) {
            var sum = this.getTotalData(serverData, headOptions)
            tableData = tableData.concat(sum)
          }

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download('访客来源分析报表' + timeStamp)
        })
      },
      // 导出表格数据执行的方法(后端)
      exportXls () {
        let data = {
          Method: 'exportImSourceAnalyse',
          Query: {
            reportType: this.id,
            includeSubordinate: this.includeSubordinate,
            user: this.$store.state.session.user._id
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.positiveSessionCount = this.positiveSessionCount
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImSessionFromReport', data)
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.sourseAreaReport') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'accessIds' }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
      })
      this.$nextTick(() => {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .area
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .el-select
        width 600px
    .primary_btn
      display inline-block
      min-width 90px
      padding 0 15px
      height 30px
      line-height 30px
      font-size 12px
      text-align center
    .map
      padding 0 26px
    .top-title
      padding-top 50px
      margin-bottom 16px
    .source-bar
      padding 4px 0
    .top-all
      height 20px
    .top-short
      height 7px
      margin-top 5px
    .colorClass
      color #985fac
    .tab
      .deploy
        .tip
          margin-left 0
</style>
